<?php

class UserAuthDatabase
{
    protected $userIdentity;
    protected $username;
    protected $password;
    
    public function __construct($username,$password)
    {
        $this->username = $username;
        $this->password = $password;
    }
    
    public function authenticate()
    {
        $authResult = 0;
        
        $newPassword = md5('sindissetima2014'.$this->password);
        
        Transaction::open();
        $db = new Repository('Usuario');
        $userList = $db->where('login', '=', $this->username)->load();
        
        if (count($userList) > 0 )
        {
            $user = $userList[0];
            if ($user->password == $newPassword )
            {
                $authResult = Authenticate::AUTH_SUCCESS;
                $this->setUser($user);
            }
            else
            {
                $authResult = Authenticate::AUTH_PASSWORD_FAILED;
            }
        }
        else
        {
            $authResult = Authenticate::AUTH_USER_NOT_FOUND;
        }
        Transaction::close();
        
        return $authResult;
    }
    
    public function getUser()
    {
        return $this->userIdentity;
    }
    
    private function setUser($user)
    {
        $userIdentity = new UserIdentity();
        $userIdentity->id = $user->id;
        $userIdentity->name = $user->nome;
        $userIdentity->username =  $user->login;
        $userIdentity->status = $user->status;        
        $this->userIdentity = $userIdentity;
    }
}

